package com.xujh;

import java.util.Map;

/**
 * <p>
 * 功能描述：支持多态性的Json公用类
 * </p>
 * <p>
 * 完成日期： 2012-04-10
 * </p>
 * @since 1.0
 * @author Gavin.Feng
 */
public class PolymorphicJsonUtil {

	/**
	 * Map to Json String
	 *
	 * */
	public static String toJson(Map<String, Object> map) throws Exception {

//		String json_str = "";

		try {
			return JacksonFactory.getPolymorphicObjectMapper()
					.writeValueAsString(map);
		} catch (Exception e) {

			throw new Exception(e);
		}

//		return json_str;
	}

	/**
	 * Object to Json
	 *
	 * */
	public static String toJson(Object obj) throws Exception {

//		String json_str = "";

		try {
			return JacksonFactory.getPolymorphicObjectMapper()
					.writeValueAsString(obj);
		} catch (Exception e) {
			throw new Exception(e);
		}

//		return json_str;
	}

	/**
	 * Json to HashMap
	 *
	 * */
	@SuppressWarnings("unchecked")
	public static Map<String, Object> genMap(String json) {

		Map<String, Object> map = null;

		try {
			map = JacksonFactory.getPolymorphicObjectMapper().readValue(json,
					Map.class);
		} catch (Exception e) {
//			throw new JsonException(e);
		}

		return map;
	}

	/**
	 * Json to Object
	 *
	 * */
	public static <T> T genObject(String json, Class<T> valueType) {

		T obj = null;

		try {
			obj = JacksonFactory.getPolymorphicObjectMapper().readValue(json,
					valueType);
		} catch (Exception e) {
//			throw new JsonException(e);
		}

		return obj;
	}

	/**
	 * @param bytes
	 * @param valueType
	 * @param <T>
	 * @return
	 * @since 1.8.0
	 */
	public static <T> T genObject(byte[] bytes, Class<T> valueType) throws Exception {
		try {
			return JacksonFactory.getPolymorphicObjectMapper().readValue(bytes, valueType);
		} catch (Exception e) {
			throw new Exception(e);
		}
	}

}
